package model

import (
	"context"
	"github.com/LyricTian/gin-admin/v7/internal/app/model/gormx/entity"
	"github.com/LyricTian/gin-admin/v7/internal/app/schema"
	"github.com/LyricTian/gin-admin/v7/pkg/errors"
)

func (a *GroupVideo) GetGroupVideo(ctx context.Context, params schema.GroupVideoQueryParam, opts ...schema.VideoQueryOptions) (*schema.VideoQueryResult, error) {

	//读取群关联的视频
	subQuery := entity.GetGroupVideoDB(ctx, a.DB).
		Select("content_id").
		Where("group_id = ?", params.GroupId).
		SubQuery()
	db := entity.GetVideoDB(ctx, a.DB).Where("id IN ?", subQuery).Where("content_type = ?", 2)
	//读取视频列表

	var opt schema.VideoQueryOptions
	if len(opts) > 0 {
		opt= opts[0]
	}
	opt.OrderFields = append(opt.OrderFields, schema.NewOrderField("created_at", schema.OrderByDESC))
	db = db.Order(ParseOrder(opt.OrderFields))

	var list entity.Videos
	pr, err := WrapPageQuery(ctx, db, params.PaginationParam, &list)
	if err != nil {
		return nil, errors.WithStack(err)
	}
	qr := &schema.VideoQueryResult{
		PageResult: pr,
		Data:       list.ToSchemaVideos(),
	}

	return qr, nil

}
